<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2018/8/14
 * Time: 15:20
 */
include 'db_connect.php';
//mysqli_select_db($con,'tieba');
$isLogin = false;
$isRegist = false;
//$isSamePsd = false;
$isUpdate = false;
$hasUpdate = false;
$successMsg = '';
$errorMsg = '';
$updateInfo = [];
$infoMsgError = '';
$psdInfoMsg = '';
$hasRegistMsg = '';
$successRegistMsg = '';
$successLoginMsg = '';
$errorLoginMsg = '';
$oldPsdErrorMsg = '';
$newPsdErrorMsg = '';
$newPsdAgainErrorMsg = '';
$updateSuccessMsg = '';
$uploadImgSuccessMsg = '';




function test_input($data)
{
    $data = trim($data);
    $data = stripslashes($data);
    $data = htmlspecialchars($data);
    return $data;
}

//判断当前用户是否登录
function init(){
    global $isLogin;
    global $successMsg;
    global $errorMsg;
    global $con;
    global $updateInfo;
    global $hasUpdate;
    //$sql = "SELECT sex, avatar, slogan FROM user WHERE ";
    //session_start();
//    $lifeTime = 1;
//    session_set_cookie_params($lifeTime);
    if (!session_id()) session_start();
    if (isset($_SESSION['user_name'])){
        $successName = $_SESSION['user_name'];
        $sql = "SELECT sex, avatar, slogan FROM user WHERE name='$successName'";
        $updateInfo = $con->query($sql);
//        while ($row = mysqli_fetch_array($updateInfo)) {
//            echo $row['sex']
//        }
        //echo "$isUpdate";
        //echo 'jjj';
        $successMsg = '用户已登录';
        //header('location:index.php');
        $isLogin = true;
        if (isset($_SESSION['user_update'])) {
            $hasUpdate = true;
        } else {
            $hasUpdate = false;
        }
    }else {
        $errorMsg = '用户未登录';
        $isLogin = false;
        //echo $isUpdate;
       // echo 'sdrfr';
        session_destroy();
    }
}

/**
 * 注册
 * @return void
 */
function regist() {
    global $isRegist;
    //global $isSamePsd;
    global $infoMsgError;
    global $psdInfoMsg;
    global $hasRegistMsg;
    global $successRegistMsg;
    //echo "执行  了";
    $t = time();
    //echo $t."<br />";
    //$add_time = date("Y年m月d日h时",$t);
    $name = $password = $passwordagain = $sex = $slogan ='';
    if ($_SERVER["REQUEST_METHOD"] == "POST") {
        $name = test_input($_POST['rname']);
        $password = md5(test_input($_POST['password']));
        $passwordagain = md5(test_input($_POST['passwordagain']));
        @$sex = $_POST['sex'];
        $slogan = test_input($_POST['slogan']);
    }
    if ($name == '' || $password == '' || $passwordagain == '' || $sex == '' || $slogan =='') {
        $infoMsgError = '信息不完整，请完善注册信息！';
        //echo "<p class='error'>信息不完整，请完善注册信息！</p>";
        return;
    }
    if ($password != $passwordagain) {
        $psdInfoMsg = '密码输入不一致，请重新输入';
        //echo "<p class='error'>密码输入不一致，请重新输入</p>";
        return;
    }
    $sql = "SELECT name, password FROM user";
    global $con;
    $result = $con->query($sql);
    while ($row = mysqli_fetch_array($result)){
        //echo $row['name']."<br />";
        if ($row['name'] == $name) {
            $hasRegistMsg = '该用户名已被注册,请重新输入用户名';
            //echo "<p class='error'>该用户名已被注册,请重新输入用户名</p>";
            return;
        }
    }
    $insets = "INSERT INTO user(name,password,sex,slogan,add_time)VALUE ('$name','$password','$sex','$slogan','$t')";
    $result1 = $con->query($insets);
    if ($result1) {
        $successRegistMsg = '注册成功';
        //echo "<p class='login'>注册成功</p>";
        $isRegist = true;
    }else {
        echo "<p class='error'>注册失败</p>";
    }
//    echo $name."<br />";
//    echo $password."<br />";
//    echo $passwordagain."<br />";
//    echo $sex."<br />";
//    echo $slogan."<br />";
    return;
}

//登录
function login() {
    $t = time();
    //global $con;
    global $successLoginMsg;
    global $errorLoginMsg;
    $name = $password ='';
    if ($_SERVER["REQUEST_METHOD"] == "POST") {
    $name = test_input($_POST['name']);
    $password = md5(test_input($_POST['password']));
}
    $sql = "SELECT id,name, password, sex, slogan, avatar FROM user";
    $updates = "UPDATE user SET login_time='$t' WHERE name='$name'";
    global $isLogin;
    global $con;
    $result = $con->query($sql);
    while($row = mysqli_fetch_array($result)) {
        //echo $row['sex']." ".$row['slogan']."<br />";
        //@session_start();
        if ($row['name'] == $name && $row['password'] == $password) {
//            $successLoginMsg = '登录成功！';
//            init();
            //echo "<p class='login'>登录成功！</p>";
            $lifeTime = 3600;
            session_set_cookie_params($lifeTime);
            session_start();
            $_SESSION['user_avatar'] = $row['avatar'];
            $_SESSION['user_name'] = $name;
            $_SESSION['user_id'] = $row['id'];
            $_SESSION['user_psd'] = $password;
            $_SESSION['user_slogan'] = $row['slogan'];
            if ($row['sex'] == 1){
                $_SESSION['user_sex'] = '男';
            }else {
                $_SESSION['user_sex'] = '女';
            }
            $con->query($updates);
            $isLogin = true;
            //header('location:index.php');
            $successLoginMsg = '登录成功！';
            //init();
            return;
        }
    }
    $errorLoginMsg = '用户名或密码错误，请重新输入！';
    //echo "<p class='error'>用户名或密码错误，请重新输入！</p>";
    return;
}
//登出
function loginout()
{
//    $lifeTime = 1;
//    session_set_cookie_params($lifeTime);
    if (!session_id()) session_start();
    if (isset($_SESSION['user_name'])) {
        session_destroy();
    }
}

//修改
function infoUpdate()
{
    global $infoMsgError;
    global $oldPsdErrorMsg;
    global $newPsdErrorMsg;
    global $newPsdAgainErrorMsg;
    global $updateSuccessMsg;
    global $isUpdate;
    global $con;
    $t = time();
    $z = '';
    $oldPsd = $newPsd = $newPsdAgain = $sex = $slogan = $sessionName ='';
    if ($_SERVER["REQUEST_METHOD"]) {
        $oldPsd = md5(test_input($_POST['oldPsd']));
        $newPsd = md5(test_input($_POST['newPsd']));
        $newPsdAgain = md5(test_input($_POST['newPsdAgain']));
        @$sex = $_POST['sex'];
        $slogan = test_input($_POST['slogan']);
        $sessionName = $_POST['sessionName'];
        $z = md5($z);
    }
//    if ($oldPsd == '' || $newPsd == '' || $newPsdAgain == '') {
//        $infoMsgError = '请完善密码信息';
//        //echo "请完善密码信息";
//        return;
//    }
    //echo $z;
    if ($oldPsd == $z || $newPsd == $z || $newPsdAgain == $z || $sex == '' || $slogan == '') {
        $infoMsgError = '信息不完整，请完善注册信息！';
        //echo "<p class='error'>信息不完整，请完善注册信息！</p>";
        return;
    }
    $sql = "SELECT password FROM user WHERE name='$sessionName'";
    $updates = "UPDATE user SET password='$newPsd', sex='$sex', slogan='$slogan', update_time='$t' WHERE name='$sessionName'";
    $result = $con->query($sql);
    while($row = mysqli_fetch_array($result)){
        //echo $row['password'];
        if ($row['password'] != $oldPsd) {
            $isUpdate = false;
            //echo $isUpdate;
            $oldPsdErrorMsg = '原密码错误';
            //echo "原误";
            return;
        } elseif ($oldPsd == $newPsd) {
            $newPsdErrorMsg = '原密码与新密码不能相同';
            $isUpdate = false;
            //echo "原密码与新密码不能相同";
            return;
        } elseif ($newPsd != $newPsdAgain) {
            $newPsdAgainErrorMsg = '新密码输入不一致';
            $isUpdate = false;
            //echo "新密码输入不一致";
            return;
        }else {
            $con->query($updates);
//            $lifeTime = 1;
//            session_set_cookie_params($lifeTime);
            if (!session_id()) session_start();
            $_SESSION['user_update'] = 1;
            $isUpdate = true;
            //echo $isUpdate;
            //init();
            $updateSuccessMsg = '修改成功';
            //echo "修改成功";
        }
    }

}

//上传头像
function uploaImg()
{
    global $isUpdate;
    global $uploadImgSuccessMsg;
    //$avatars = '';
    global $con;
    $t = time();
    //echo $_SESSION['user_name'];
    if ($_FILES["file"]["error"] > 0)
    {
        echo "错误：" . $_FILES["file"]["error"] . "<br>";
    }
    else
    {
//        echo "上传文件名: " . $_FILES["file"]["name"] . "<br>";
//        echo "文件类型: " . $_FILES["file"]["type"] . "<br>";
//        echo "文件大小: " . ($_FILES["file"]["size"] / 1024) . " kB<br>";
        //echo "文件临时存储的位置: " . $_FILES["file"]["tmp_name"];
    }
    if (file_exists("upload/".$_FILES["file"]["name"])) {
        //echo $_FILES["file"]["name"]."文件已经存在.";
        $avatars = "upload/".$_FILES["file"]["name"];
    } else {
        move_uploaded_file($_FILES["file"]["tmp_name"],"upload/".$_FILES["file"]["name"]);
        //echo "文件已经被存储到:"."upload/".$_FILES["file"]["name"];
        $avatars = "upload/".$_FILES["file"]["name"];
    }
    //session_start();
    $sessionName = $_POST['sessionName'];
    //echo $sessionName;
    $updates = "UPDATE user SET avatar='$avatars', update_time='$t' WHERE name='$sessionName'";
    if (isset($sessionName)) {
        $con->query($updates);
        $uploadImgSuccessMsg = '头像上传成功！';
//        $lifeTime = 1;
//        session_set_cookie_params($lifeTime);
        if (!session_id()) session_start();
        $_SESSION['user_update'] = 1;
        $isUpdate = true;
    }
}

/**
 *
 * @return void
 */
function main(){
    //global $isUpdate;
    $post = $_POST;
    $act = '';

    isset($post['act']) && $act = $post['act'];
    if($act == 'regist'){
        regist();
        return ;
    }

    if($act == 'login'){
        login();
        return ;
    }

    if ($act == 'loginout') {
        loginout();
        return;
    }

    if ($act == 'update') {
        infoUpdate();
    }

    if ($act == 'uploaImg')
    {
        uploaImg();
    }

    init();
    //echo $isUpdate;
}
//echo $isUpdate;
main();
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>用户中心</title>
    <style>
        .error {
            color: #f00;
        }
        .login {
            color: #0f0;
        }
    </style>
</head>
<body>
<?php include 'public/head.php'; ?>
<?php if($isLogin){ ?>
    <h1><?php echo $_SESSION['user_name']." 欢迎您！";?></h1>
<?php if ($hasUpdate) {?>
    <?php foreach($updateInfo as $k => $v) { ?>
    头像<img src="<?php echo $v['avatar']; ?>" alt="" width="100">
    <h3>性别:<?php
        if($v['sex'] == 1) {
            echo '男';
        }else {
            echo '女';
        }
        ?></h3>
    <h3>签名:<?php echo $v['slogan']; ?></h3>
    <?php } ?>
<?php } else { ?>
        头像<img src="<?php echo $_SESSION['user_avatar']; ?>" alt="" width="100">
        <h3>性别:<?php echo $_SESSION['user_sex'];?></h3>
        <h3>签名:<?php echo $_SESSION['user_slogan'];?></h3>
<?php } ?>
    <p class="login"><?php echo $successMsg; ?></p>
    <?php $sessionName = $_SESSION['user_name']; ?>
    <form action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>" method="post">
        <fieldset>
            <legend>修改用户信息</legend>
            修改密码:<br />
            原密码:<input type="password" name="oldPsd"><br />
            新密码:<input type="password" name="newPsd"><br />
            确认密码:<input type="password" name="newPsdAgain"><br />
            修改性别:<br />
            <input type="radio" name="sex" value="1"<?php if (isset($_POST['sex']) && $_POST['sex'] == 1 && $isUpdate == false) {?>
                checked
            <?php } ?>
            >男
            <input type="radio" name="sex" value="0"<?php if (isset($_POST['sex']) && $_POST['sex'] == 0 && $isUpdate == false) {?>
                checked
            <?php } ?>
            >女<br />
            修改签名:<br />
            <textarea name="slogan" id="" cols="30" rows="10"><?php if (isset($_POST['slogan']) && $isUpdate == false) {echo test_input($_POST['slogan']);} ?></textarea><br />
            <input type="hidden" name="act" value="update">
            <input type="hidden" name="sessionName" value="<?php echo $sessionName; ?>">
            <input type="submit" value="提交">
        </fieldset>
    </form>
    <?php if (isset($infoMsgError)) {?>
        <p class="error"><?php echo $infoMsgError; ?></p>
    <?php } ?>
    <?php if (isset($oldPsdErrorMsg)) {?>
        <p class="error"><?php echo $oldPsdErrorMsg; ?></p>
    <?php } ?>
    <?php if (isset($newPsdErrorMsg)) {?>
        <p class="error"><?php echo $newPsdErrorMsg; ?></p>
    <?php } ?>
    <?php if (isset($newPsdAgainErrorMsg)) {?>
        <p class="error"><?php echo $newPsdAgainErrorMsg; ?></p>
    <?php } ?>
    <?php if (isset($updateSuccessMsg)) {?>
        <p class="login"><?php echo $updateSuccessMsg; ?></p>
    <?php } ?>
    <form action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>" method="post" enctype="multipart/form-data">
        <fieldset>
            <legend>上传头像</legend>
            <label for="file">文件名:</label>
            <input type="file" name="file" id="file"><br />
            <input type="hidden" name="act" value="uploaImg">
            <input type="hidden" name="sessionName" value="<?php echo $sessionName; ?>">
            <input type="submit" value="提交">
        </fieldset>
    </form>
    <?php if (isset($uploadImgSuccessMsg)) {?>
        <p class="login"><?php echo $uploadImgSuccessMsg; ?></p>
    <?php } ?>
<form action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>" method="post">
    <fieldset>
        <legend>退出登录</legend>
        <input type="hidden" name="act" value="loginout">
        <input type="submit" value="登出">
    </fieldset>
</form>
<?php } else { ?>
    <p class="error"><?php echo $errorMsg; ?></p>
<form action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>" method="post">
    <fieldset>
        <legend>注册</legend>
        用户名：<input type="text" name="rname" <?php if (isset($_POST['rname']) && $isRegist == false) { ?>
            value="<?php echo test_input($_POST['rname']); ?>"
            <?php } else {?>
                value=" "
            <?php } ?>
        ><br />
        密码：<input type="password" name="password"><br />
        确认密码：<input type="password" name="passwordagain"><br>
        性别：<input type="radio" name="sex" value="1" <?php if (isset($_POST['sex']) && $_POST['sex'] == 1 && $isRegist == false) {?>
                checked
             <?php } ?>
             >男
             <input type="radio" name="sex" value="0"<?php if (isset($_POST['sex']) && $_POST['sex'] == 0 && $isRegist == false) {?>
                 checked
             <?php } ?>
             >女<br />
        签名：<textarea name="slogan" id="" cols="30" rows="10"><?php if (isset($_POST['slogan']) && $isRegist == false) {echo test_input($_POST['slogan']);} ?>
             </textarea><br />
             <input type="hidden" name="act" value="regist">
             <input type="submit" value="提交">
    </fieldset>
</form>
    <?php if (isset($infoMsgError)) {?>
        <p class="error"><?php echo $infoMsgError; ?></p>
    <?php } ?>
    <?php if (isset($psdInfoMsg)) {?>
        <p class="error"><?php echo $psdInfoMsg; ?></p>
    <?php } ?>
    <?php if (isset($hasRegistMsg)) {?>
        <p class="error"><?php echo $hasRegistMsg; ?></p>
    <?php } ?>
    <?php if (isset($successRegistMsg)) {?>
        <p class="login"><?php echo $successRegistMsg; ?></p>
    <?php } ?>

<form action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>" method="post">
    <fieldset>
        <legend>登录</legend>
        用户名：<input type="text" name="name"><br />
        密码：<input type="password" name="password"><br />
        <input type="hidden" name="act" value="login">
        <input type="submit" value="提交">
    </fieldset>
</form>
    <?php if (isset($successLoginMsg)) {?>
        <p class="login"><?php echo $successLoginMsg; ?></p>
    <?php } ?>
    <?php if (isset($errorLoginMsg)) {?>
        <p class="error"><?php echo $errorLoginMsg; ?></p>
    <?php } ?>
<?php } ?>

</body>
</html>


